#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: AKSK.py 
@version:
@time: 2021/09/08 
"""
# AKSK
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
access_token = "v8L5dkNmw41rrhmoGfqODy2CUe9xjixR"
secret_key = "uXygQZvNZLvFwft7GrpchdP6KmXZfA11"
import random
import time
from urllib import parse
import base64
import hashlib
import hmac


def randomStr(count):
    count = count if count >= 0 else 0
    lens = len(chars)
    strs = ""
    while True:
        count -= 1
        if count == 0:
            return strs
        strs += str(int(float(random.random() * lens)))


def ts():
    _ = int(time.time() * 1000)

    # def date_time_mill(ls):
    #     return int(time.mktime(ls.timetuple()) * 1000)

    return str(_)


params = {
    "ts": ts(),
    "nonce": randomStr(10),
    "signVersion": "1.0",
    "accessKey": access_token,
    "sign": "dfs",
}


def canonicalQueryString(ls):
    t = "&"
    lis = []
    for i in sorted(ls):
        if i == "sign":
            continue
        tmp = str(parse.quote(i)) + "=" + str(parse.quote(ls[i]))
        lis.append(tmp)
    s = t.join(lis)
    return s


def canonicalQueryString2(ls):
    t = "&"
    lis = []
    for i in sorted(ls):
        tmp = str(parse.quote(i)) + "=" + str(parse.quote(ls[i]))
        lis.append(tmp)
    s = t.join(lis)
    return s


def hash_hmac(text, ac_key=secret_key):
    res = hmac.new(bytes(ac_key, 'utf-8'), bytes(text, 'utf-8'), digestmod=hashlib.sha1).digest()
    t = base64.b64encode(res)
    return t


def data_str(method, payload=None):
    if method == "GET":
        print("GET:" + canonicalQueryString(params))
        params["sign"] = hash_hmac("GET:" + canonicalQueryString(params) + ":")
    elif method == "POST":
        params["sign"] = hash_hmac("POST:" + canonicalQueryString(params) + ":" + payload)
    elif method == "DELETE":
        params["sign"] = hash_hmac("DELETE:" + canonicalQueryString(params) + ":")
    elif method == "WS":
        params["sign"] = hash_hmac(canonicalQueryString(params))
    return params


def ws_params():
    return canonicalQueryString2(data_str("WS"))


if __name__ == '__main__':
    print(ws_params())
